package com.anycc.cloud.core.interceptor;

import com.anycc.cloud.core.config.ServiceConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * user context filter
 */
@Component
public class UserContextFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(UserContextFilter.class);
    private static final String CHARSET_NAME = "UTF-8";
    private static final String USER_NAME = "user_name";

    @Autowired
    private ServiceConfig serviceConfig;


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        if(httpServletRequest.getHeader(UserContext.JWT)!=null) {//如果首部没有jwt，则直接跳过过滤器
            try {
                Claims claims = Jwts.parser().setSigningKey(serviceConfig.getJwtSigningKey().getBytes(CHARSET_NAME)).parseClaimsJws(httpServletRequest.getHeader(UserContext.JWT)).getBody();
                UserContextHolder.getContext().setUsername((String) claims.get(USER_NAME));
            } catch (Exception e) {
                UserContextHolder.getContext().setUsername(null);
                logger.warn("JWT decode fail,Anycc Cloud username: {}", UserContextHolder.getContext().getUsername());
            }
        }
        filterChain.doFilter(httpServletRequest, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }


    @Override
    public void destroy() {
    }
}
